<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/4/23
 * Time: 17:55
 */
namespace app\api\controller;

use app\api\model\verticalDb;
use think\Controller;
use think\Request;
use think\Db;
use Qcloud\Sms\SmsSingleSender;

/**
 * 2019/9/18接口
 */
class Verify extends Common{

    private  $appid = '1400202934';  //腾讯云短信APPID
    private  $appkey  = '6540b3b5e0cd58d4ad06820159b16795'; //key
    private  $sendTime  = '60'; //发送间隔时间
    private  $pastTime  = '300'; //验证码过期时间  5分钟

    /**
     * 手机认证--获取验证码
     * mobile  手机
     * uid   用户ID
     * sKey   用户key
     */
    public function getSmsCode(){
        if (Request::instance()->isPost()) {
            $post_data = input('post.');
            //用户ID是否存在
            $u_where = [
                'uid'=>$post_data['uid'],
                'S_key'=>$post_data['sKey'],
            ];
            $u_data = Db::table('role_info')->where($u_where)->find();
            if (empty($u_data)) {
                self::$result_data['msg'] = '用户ID不存在';
                $this->returnJson(self::$result_data);
            }
            //校验手机号
            if (!preg_match("/^1[34578]\d{9}$/", $post_data['mobile'])) {
                self::$result_data['msg'] = '手机号格式有误';
                $this->returnJson(self::$result_data);
            }
            //校验手机号是否已经注册过
            $isUse = Db::table('account_info')->where('MobilePhone', $post_data['mobile'])->find();
            if($isUse){
                self::$result_data['msg'] = '手机号已被使用';
                $this->returnJson(self::$result_data);
            }

            //每隔多久才能发送下一条
            $vRes = Db::table('tf_ver_code')->where('mobile', $post_data['mobile'])->order('id desc')->find();
            if((time() - strtotime($vRes['created_time'])) > $this->sendTime){

            }else{
                self::$result_data['msg'] = $this->sendTime -  (time() - strtotime($vRes['created_time'])).'秒后才能继续发送';
                $this->returnJson(self::$result_data);
            }
            try {
                $msg = [
                    'uid' => $post_data['uid'],
                    'mobile' => $post_data['mobile'],
                    'code' => rand('100000', '999999'),
                    'created_time' => date('Y-m-d H:i:s')
                ];
                $ssender = new SmsSingleSender($this->appid, $this->appkey);
                $fz = $this->pastTime/60;
                $content = $msg['code'] . "为您的手机认证验证码，请于".$fz."分钟内填写。如非本人操作，请忽略本短信。";
                $result = $ssender->send(0, "86", $msg['mobile'], $content, '', '');
                $rsp = json_decode($result, true);
                if ($rsp['errmsg'] == 'OK') {
                    //发送成功  保存至数据库
                    $res = Db::table('tf_ver_code')->insert($msg);
                    if ($res) {
                        self::$result_data['msg'] = '发送成功';
                        self::$result_data['code'] = 1;
                        $this->returnJson(self::$result_data);
                    }
                } else {
                    self::$result_data['msg'] = '发送失败';
                    self::$result_data['data'] = $rsp['errmsg'];
                    $this->returnJson(self::$result_data);
                }
            } catch (\Exception $e) {
                echo var_dump($e);
            };
        }
    }


    /**
     * 验证手机验证码
     * uid  用户ID
     * mobile  手机
     * code     验证码
     */
    public function verifyCode(){
        if (Request::instance()->isPost()) {
            $post_data = input('post.');
            $u_where = [
                'uid'=>$post_data['uid'],
                'S_key'=>$post_data['sKey'],
            ];
            $u_data = Db::table('role_info')->where($u_where)->find();
            if (empty($u_data)) {
                self::$result_data['msg'] = '用户ID不存在';
                $this->returnJson(self::$result_data);
            }
            //校验手机号
            if (!preg_match("/^1[34578]\d{9}$/", $post_data['mobile'])) {
                self::$result_data['msg'] = '手机号格式有误';
                $this->returnJson(self::$result_data);
            }
            //校验验证码是否正确
            $vRes = Db::table('tf_ver_code')->where(['mobile'=>$post_data['mobile'],'uid'=>$post_data['uid']] )->order('id desc')->find();
            if(empty($post_data['code']) || $post_data['code'] != $vRes['code']){
                self::$result_data['msg'] = '验证码错误';
                $this->returnJson(self::$result_data);
            }
            if((time() - strtotime($vRes['created_time'])) > $this->pastTime){
                self::$result_data['msg'] = '验证码已过期';
                $this->returnJson(self::$result_data);
            }
            //根据uid保存数据库并修改状态
            $update_data = [
                'MobilePhone'=>$post_data['mobile'],
            ];
            $res = Db::table('account_info')->where('uid',$post_data['uid'])->update($update_data);
            if($res){
                self::$result_data['msg'] = '操作成功';
                self::$result_data['code'] = 1;
                $this->returnJson(self::$result_data);
            }
        }
    }

    /**
     * 1.手机注册,生成验证码
     * @param mobile
     */
    public function mobileReg(Request $request){
        if (Request::instance()->isPost()) {
            $param = $request->param();
            //校验正确的手机号
            if(!$this->is_mobile($param['mobile'])){
                self::$result_data['msg'] = '手机号码有误';
                return $this->returnJson(self::$result_data);
            }
            $model = new verticalDb();
            $insertData = [
                'mobile'=>$param['mobile'],
                'login_key'=>rand(1000,9999),
                'CreateDate'=>date('Y-m-d H:i:s',time()),
                'ip'=>$this->getUserIpAddr(),
            ];
            $model->table('account_mobile_key')->insertGetId($insertData);
            self::$result_data['code'] = 1;
            self::$result_data['msg'] = '';
            self::$result_data['data'] = $insertData;
            return $this->returnJson(self::$result_data);
        }
    }

    /**
     * 2、找回密码，生成验证码
     * @param mobile
     */
    public function findPassword(Request $request){
        $this->mobileReg($request);
    }

    /**
     * 实名认证
     * uid   用户id
     * sKey   用户key
     * idCardNo   身份证号码
     * realName   姓名
     *
     */
    public function realNameAuth(Request $request){
        if (Request::instance()->isPost()) {
            $param = $request->param();
            $vf = new Verifyfield();
            $fRes = $vf->field1($param);
            if($fRes){
                self::$result_data['msg'] = $fRes;
                $this->returnJson(self::$result_data);
            }

            //验证用户
            $res = $vf->verifyUser($param['uid'],$param['sKey']);
            if(!$res){
                self::$result_data['msg'] = '用户ID不存在';
                $this->returnJson(self::$result_data);
            }

            //验证身份证合法性和唯一性
            if(!$this->is_idcard($param['idCardNo'])){
                self::$result_data['msg'] = '身份证号码错误';
                $this->returnJson(self::$result_data);
            }
            //校验身份证是否已经注册过
            $isUse = Db::table('account_info')->where('ID_card_no', $param['idCardNo'])->find();
            if($isUse){
                self::$result_data['msg'] = '身份证号已被使用';
                $this->returnJson(self::$result_data);
            }

            //验证姓名
            if(!$this->isAllChinese($param['realName'])){
                self::$result_data['msg'] = '请输入中文名';
                $this->returnJson(self::$result_data);
            }

            //调接口验证身份证号码和姓名
            $fRes = $vf->vfSfz($param);
            if($fRes){
                self::$result_data['msg'] = $fRes;
                $this->returnJson(self::$result_data);
            }
            //保存身份证信息
            //根据uid保存数据库并修改状态
            $insertData = [
                'ID_card_no'=>$param['idCardNo'],
                'RealName'=>$param['realName'],
                'is_real'=>1,
            ];
            $res = Db::table('account_info')->where('uid',$param['uid'])->update($insertData);
            if($res){
                $this->result_data['msg'] = '操作成功';
                $this->result_data['code'] = 1;
                $this->returnJson($this->result_data);
            }

        }
    }

    /**
     * 预登陆服务器
     * account  唯一openId
     */
    public function readyLoginServer(Request $request){
        if (Request::instance()->isPost()) {
            $param = $request->param();
            $vf = new Verifyfield();
            $fRes = $vf->field2($param);
            if($fRes){
                self::$result_data['msg'] = $fRes;
                $this->returnJson(self::$result_data);
            }
            //生成loginKey
            $login_key = $vf->nonceStr(10);
            //获取Ip
            $ip = $this->getUserIpAddr();
            //获取子游戏配置
            $gameData = Db::table('gameinfo')->where('IS_LINE','<>',1)->select();
            //删除历史登录数据
            DB::table('account_info_login')->where('account',$param['account'])->delete();
            //插入新的登录数据
            $insertData = [
                'account'=>$param['account'],
                'ip'=>$ip,
                'login_key'=>$login_key,
                'CreateDate'=>date('Y-m-d H:i:s',time()),
            ];
            $id = DB::table('account_info_login')->insertGetId($insertData);
            //搜索用户新的登录数据和用户信息
            $clubData = DB::table('club_server')->select();
            $loginData = DB::table('account_info_login')->where('account',$param['account'])->find();
            //返回数据
            self::$result_data['code'] = 1;
            self::$result_data['data'] = [
                'clubData'=>$clubData,
                'loginData'=>$loginData,
                'gameData'=>$gameData,
            ];
            $this->returnJson(self::$result_data);
        }
    }

    /**
     * 获取战绩详情
     * scoreId  房号ID
     */
    public function getRecordInfo(Request $request){
        if (Request::instance()->isPost()) {
            $param = $request->param();
            $vf = new Verifyfield();
            $fRes = $vf->field3($param);
            if($fRes){
                self::$result_data['msg'] = $fRes;
                $this->returnJson(self::$result_data);
            }
            //验证用户
            $res = $vf->verifyUser($param['uid'],$param['sKey']);
            if(!$res){
                self::$result_data['msg'] = '用户ID不存在';
                $this->returnJson(self::$result_data);
            }

            //获取战绩详情
            $recordData = Db::table('record_tableplay')->where('ScoreID',$param['scoreId'])->find();
            self::$result_data['code'] = 1;
            self::$result_data['data'] = [
                'recordData'=>$recordData,
            ];
            $this->returnJson(self::$result_data);
        }

    }


}